package cn.icanci.loopstack.rec.engine.sdk.factor;

import cn.icanci.loopstack.rec.common.aggregation.model.BaseDataDTO;
import cn.icanci.loopstack.rec.common.aggregation.model.StrategyDTO;
import cn.icanci.loopstack.rec.common.enums.DataTypeEnum;
import cn.icanci.loopstack.rec.common.enums.OperatorEnum;
import cn.icanci.loopstack.rec.common.utils.DateUtils;

import java.math.BigDecimal;
import java.util.Objects;

import javax.script.Bindings;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @author icanci
 * @since 1.0 Created in 2022/11/16 22:35
 */
@Component
@FactorBean(OperatorEnum.EQ)
public class EQFactor extends AbstractFactor {

    @Override
    public boolean match(Bindings bindings, StrategyDTO.ConditionCell conditionCell, String domainCode) {
        BaseDataDTO baseData = engineRepositoryHolder.getBaseData(domainCode, conditionCell.getLeftValue());
        String leftValue = getValue(bindings, baseData);
        String rightValue = conditionCell.getRightValue();
        DataTypeEnum dataType = DataTypeEnum.valueOf(baseData.getDataType());
        switch (dataType) {
            case BOOLEAN:
                return StringUtils.equalsIgnoreCase(leftValue, rightValue);
            case DATE:
                return Objects.requireNonNull(DateUtils.parse(leftValue, DateUtils.FormatType.YYYY_MM_DD_HH_MM_SS)).compareTo(DateUtils.parse(rightValue,  DateUtils.FormatType.YYYY_MM_DD_HH_MM_SS)) == 0;
            case NUMBER:
                return new BigDecimal(leftValue).compareTo(new BigDecimal(rightValue)) == 0;
            case STRING:
            case METADATA:
                return StringUtils.equals(leftValue, rightValue);
            default:
                // no op
        }
        return false;
    }
}
